using System.Collections.Generic;
using System.Linq;
using System.Drawing;
using Tiwo.Design.Renderers;
using Tiwo.Design.Trackers;

namespace Tiwo.Design.ItemRenderers
{
    public class ResizeRectangularModificator : MoveRectangularModificator
    {
        public const float DragAreaGap = 4;

        public ResizeRectangularModificator(RectangularRenderer renderer)
            : base(renderer)
        {
        }

        public override IMouseTracker CreateMouseTracker(PointF location)
        {
            return CreateResizeTracker(location) ?? base.CreateMouseTracker(location);
        }

        private IMouseTracker CreateResizeTracker(PointF location)
        {
            var areas = CreateResizeAreas(Renderer);

            var item = areas.Where(k => k.Value.Contains(location));
            if (item.Count() == 0)
                return null;
            return new ResizeRendererMouseTracker(Renderer, item.First().Key);
        }

        public static IDictionary<ResizeDirection, RectangleF> CreateResizeAreas(RectangularRenderer renderer)
        {
            var leftOuterBorder = renderer.Location.X - DragAreaGap;
            var semiWidthBorder = renderer.Location.X + renderer.Size.Width / 2 - DragAreaGap;
            var rightInnerBorder = renderer.Location.X + renderer.Size.Width - DragAreaGap;

            var topOuterBorder = renderer.Location.Y - DragAreaGap;
            var semiHeightBorder = renderer.Location.Y + renderer.Size.Height / 2 - DragAreaGap;
            var bottomInnerBorder = renderer.Location.Y + renderer.Size.Height - DragAreaGap;

            return new Dictionary<ResizeDirection, RectangleF>
            {
            {ResizeDirection.Top|ResizeDirection.Left, new RectangleF(leftOuterBorder, topOuterBorder, 2 * DragAreaGap, 2 * DragAreaGap) },
            {ResizeDirection.Left, new RectangleF(leftOuterBorder,semiHeightBorder, 2 * DragAreaGap, 2 * DragAreaGap)},
            {ResizeDirection.Bottom|ResizeDirection.Left, new RectangleF(leftOuterBorder, bottomInnerBorder, 2 * DragAreaGap,2 * DragAreaGap)},
            {ResizeDirection.Bottom, new RectangleF(semiWidthBorder,bottomInnerBorder, 2 * DragAreaGap, 2 * DragAreaGap)},
            {ResizeDirection.Bottom|ResizeDirection.Right, new RectangleF(rightInnerBorder, bottomInnerBorder, 2 * DragAreaGap, 2 * DragAreaGap)},
            {ResizeDirection.Right, new RectangleF(rightInnerBorder,semiHeightBorder, 2 * DragAreaGap, 2 * DragAreaGap)},
            {ResizeDirection.Top|ResizeDirection.Right, new RectangleF(rightInnerBorder,topOuterBorder, 2 * DragAreaGap, 2 * DragAreaGap)},
            {ResizeDirection.Top, new RectangleF(semiWidthBorder,topOuterBorder, 2 * DragAreaGap, 2 * DragAreaGap)}
            };
        }
    }
}